/*
 * Creator:     ML
 * CreatDate:   2020-06-15
 * descripts：  贫困户配置
 * */
import React from 'react';
import { Select, Input, Row, Col, Button, Spin, Divider, Popconfirm, message, Icon, Form,Table, Modal, Card, Switch, DatePicker, Popover, List } from 'antd';
import { $http } from 'containers/config/https';
import 'assets/css/system.css';
import store from 'store/index';
import moment from 'moment';
import PoorConfigModal from './component/PoorConfigModal.jsx';
import CommonPagination from 'components/pagination';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';

const { Option } = Select;
const FormItem = Form.Item;

const formItemLayout = {
  labelCol: { span: 10 },
  wrapperCol: { span: 14 },
}
const paddRightCol = {
  paddingRight: "0px",
  paddingLeft: "10px"
}
const formItemLayoutType = {
  labelCol: { span: 2 },
  wrapperCol: { span: 22 }
}
const formItemLayoutTop = {
  labelCol: { span: 9 },
  wrapperCol: { span: 15 },
}
const formItemLayout717 = {
  labelCol: { span: 7 },
  wrapperCol: { span: 17 },
}

class PoorHouseholdsConfig extends React.Component {
  constructor() {
    super();
    this.state = {
      // 角色名称
      name: undefined,
      // 关联岗位
      quarters: undefined,
      // 记录状态
      status: undefined,
      // 表格数据
      tableData: [],
      // 表格数据总条数
      total: 0,
      showLoading: true,
      page: 1,
      pageSize: 20,
      selectData: {}, // 下拉框数据
      headerHeight: 0,
      defaultFlag: false,
      modalVisible: false,
      editData: {},
      total: 0,
      page: 1,
      pageSize: 20,
      size: "small",
      search: "",
      columns:[]
    };
    // this.columns = [
    //   {
    //     key: 1,
    //     title: '姓名',
    //     dataIndex: 'groupDesc',
    //     align: "center",
    //     width: 80
    //   },
    //   {
    //     key: 2,
    //     title: '证件类型',
    //     dataIndex: 'cardTypeDesc',
    //     align: "center",
    //     width: 100
    //   },
    //   {
    //     key: 3,
    //     title: '人数',
    //     dataIndex: 'sexDesc',
    //     align: "center",
    //     width: 80
    //   },
    //   {
    //     key: 5,
    //     title: '与户主关系',
    //     dataIndex: 'nationDesc',
    //     align: "center",
    //     width: 100
    //   },
    //   {
    //     key: 6,
    //     title: '民族',
    //     dataIndex: 'patTypeDesc',
    //     align: "center",
    //     width: 100
    //   },
    //   {
    //     key: 7,
    //     title: '文化程度',
    //     dataIndex: 'patTypeDesc',
    //     align: "center",
    //     width:100
    //   },
    //   {
    //     key: 8,
    //     title: '健康状况',
    //     dataIndex: 'patTypeDesc',
    //     align: "center",
    //     width: 120
    //   },
    //   {
    //     key: 11,
    //     title: '劳动技能',
    //     dataIndex: 'patTypeDesc',
    //     align: "center",
    //     width: 120
    //   }, {
    //     key: 12,
    //     title: '贫困属性',
    //     dataIndex: 'patTypeDesc',
    //     align: "center",
    //     width:80
    //   }, {
    //     key: 13,
    //     title: '脱贫年度',
    //     dataIndex: 'patTypeDesc',
    //     align: "center",
    //     width: 160
    //   },{
    //     key: 14,
    //     title: '首次识别时间',
    //     dataIndex: 'patTypeDesc',
    //     align: "center",
    //     width: 150
    //   },{
    //     key: 15,
    //     title: '贫困人员识别时间',
    //     dataIndex: 'patTypeDesc',
    //     align: "center",
    //     width: 150
    //   },
    //   {
    //     key: 9,
    //     title: '地址',
    //     dataIndex: 'provDesc',
    //     align: "center",
    //     width: 260,
    //     render: (text, record) => {
    //       let add = record.provinceDesc + '，' + record.cityDesc + '，' + record.areaDesc;
    //       add = record.villageDesc ? add + '，' + record.villageDesc : add;
    //       add = record.hamletDesc ? add + '，' + record.hamletDesc : add;
    //       return <span>{add}</span>
    //     }
    //   },
    //   {
    //     title: '操作',
    //     key: 10,
    //     align: "center",
    //     width: 130,
    //     fixed: 'right',
    //     render: (text, record) => (
    //       <span>
    //         <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
    //         <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
    //         <Divider type="vertical" />
    //         <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
    //         <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDetele(record)} >
    //           <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
    //         </Popconfirm>
    //       </span>
    //     ),
    //   }
    // ]

  }

  componentDidMount() {
    // 初始化列表数据
    this.handleQuery();
    // 组件加载完毕关闭loading
    this.setState({ showLoading: false });
    this.getBaseParams()
    this.getMainTableColumns()
  }
   //动态表头
   onColumnRef = (ref) => {
    this.columnRef = ref;
}
  // 获取主列表columns
  getMainTableColumns = () => {
    let data = {
        params: [{
            compontName: "PoorHouseholdInformation",
            reactCode: ['PoorHouseholdInformation'],
            type: 'C',
        }]
    }
    $http.post('urlS', this, {
        code: '01040073',
        data: data,
        success: function (res) {
            if (+res.errorCode === 0) {
                let arr = res.result && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map(item => {
                    return {
                        align: item.align,
                        widthNum: parseInt(item.width),
                        width: item.width,
                        dataIndex: item.dataIndex,
                        title: <div onDoubleClick={() => this.columnRef.onOpenModel()}>{item.title}</div>,
                        display: item.display,
                        key: item.seqNo,
                        // render: (text, record) => {
                        //    if (item.code == "status") {
                        //      return (
                        //      <span>{record.status=="Y"?"生效":"失效"}</span>
                        //      )
                        //    }
                        //    return text
                        //  }
                    }
                }) : '';
                let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                let seqArr = {
                    align: "center",
                    widthNum: 140,
                    width: "160px",
                    code: "edit",
                    dataIndex: "edit",
                    title: "操作",
                    display: "Y",
                    render: (text, record) => (
                      <span>
                        <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
                        <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
                        <Divider type="vertical" />
                        <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
                        <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDetele(record)} >
                          <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
                        </Popconfirm>
                      </span>
                    ),
                }
                filterArr.push(seqArr)
                this.setState({ columns: filterArr, widthTotal: res.totalWidth })
                // console.log("res.totalWidth",res.totalWidth)
            }
        }
    })
}
  //获取对应的医院基础信息数据
  getBaseParams = () => {
    let data = {
      params: [{
        hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : ''
      }],
    }
    $http.post("urlS", this, {
      code: "01040059",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({
            cardType: res.cardType
          })
        } else {

        }
      },
      error: function (error) {

      }
    });
    $http.post("urlS", this, {
      code: "03030027",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({
            group: res.result.Data
          })
        } else {

        }
      },
      error: function (error) {

      }
    });
  }

  componentWillUnmount() {
    // 组件销毁前将静止让setState修改state的状态
    this.setState = (state, callback) => { return; }
  }
  modalRef = (ref) => {
    this.modalChildRef = ref
  }

  // 请求列表数据
  getTableData() {
    let { page, pageSize } = this.state;
    let data = {};
    this.props.form.validateFields((error, values) => {
      if (error) {
        return;
      }
      data = {
        params: [{
          patIDCardNo: values && values.patIDCardNo ? values.patIDCardNo : '',
          patName: values && values.patName ? values.patName : '',
        }],
        pagination: [{
          pageSize: pageSize,
          currentPage: page,
          sortColumn: "",
          sortOrder: ""
        }]
      };
      $http.post('urlS', this, {
        code: "03030093",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.result) {
            this.setState({ tableData: res.result.data, total: res.result.TotalCount }, () => {
              // 数据加载成功关闭loading
            })
          } else {
            this.setState({ tableData: [], total: 0 }, () => {
              // 数据加载成功关闭loading
            })
          }
        },
        error: function () {
          this.setState({ tableData: [], total: 0 }, () => {
            // 数据加载成功关闭loading
          })
        }
      });
    });

  }
  // 修改page和pageSize 跳转至---
  onChange = (e) => {
    this.setState({ page: e, pageSize: this.state.pageSize, }, () => {
      // 重新调用查询方法
      this.getTableData();
    })
  }
  //下拉选择页数
  onShowSizeChange = (page, pageSize) => {
    // console.log("page",page,"pagesize",pageSize)
    this.setState({ page: 1, pageSize: pageSize, search: "search" }, () => {
      // 重新调用查询方法
      this.getTableData();
    })
  }
  // 显示分页总条数
  showTotal(total) {
    return `共 ${total} 条`;
  }
  // 查询
  handleQuery = () => {
    this.setState({ page: 1, pageSize: this.state.pageSize, search: "search" }, () => {
      // 重新调用查询方法
      this.getTableData();
    })
  }

  // 新增跳转到新增界面
  handleAdd = () => {
    this.modalChildRef.showModal({}, "")
  }
  handleDetele = (record) => {
    let data = {
      params: [{
        updateUserID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
        ID: record.ID
      }]
    }
    $http.post('urlADS', this, {
      code: '03030094',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success('删除成功');
          // 刷新列表数据
          this.handleQuery();
        }
      }
    })
  }
  // 编辑
  handleCompile = (record) => {
    this.modalChildRef.showModal(record, "1")
  }
  setDefaultFlag = (v) => {
    this.setState({ defaultFlag: v });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const { cardType, group } = this.state
    // 组件所需参数
    const param = {
      // 表头配置
      columns: this.state.columns,
      // 表格数据
      data: this.state.tableData,
      // 数据总条数
      total: this.state.total,
      // 当前页数
      page: this.state.page,
      // 表格的宽度
      x: '100%',
      y: store.getState().tableHeight.y + 81 - this.state.headerHeight,
      height: store.getState().tableHeight.y + 50 - this.state.headerHeight + 'px',
    }
    //  // 医院
    //  let supHealthBurOps = []
    //  supHealthBur && supHealthBur.map(item => {
    //      supHealthBurOps.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
    //    })
    // 角色
    let groupOpt = []
    group && group.map(item => {
      groupOpt.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
    })
    // 卡类型
    let cardTypeOpt = []
    cardType && cardType.map(item => {
      cardTypeOpt.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
    })
    return (
      <Spin tip="加载中..." spinning={this.state.showLoading}>
        <div>
          <Form>
            <Row style={{ margin: '23px 0 0 0' }}>
              {/* <Col span={3} >
                <FormItem {...formItemLayoutTop} label='医院'>
                  {getFieldDecorator('hospID', {
                    initialValue: undefined,
                    rules: [{ required: false, message: '' }],
                  })(
                    <Select showSearch allowClear optionFilterProp="role" >
                      {supHealthBurOps}
                    </Select>
                  )}
                </FormItem>
              </Col> */}
              <Col span={3} >
                <FormItem {...formItemLayoutTop} label='姓名'>
                  {getFieldDecorator('patName', {
                    initialValue: undefined,
                    rules: [{ required: false, message: '' }],
                  })(
                   <Input />
                  )}
                </FormItem>
              </Col>
              <Col span={5} >
                <FormItem {...formItemLayout717} label='证件号码'>
                  {getFieldDecorator('patIDCardNo', {
                    initialValue: undefined,
                    rules: [{ required: false, message: '' }],
                  })(
                    <Input />
                  )}
                </FormItem>
              </Col>
              <Col span={1} style={{ margin: "0 16px" }}>
                <FormItem {...formItemLayout}>
                  {getFieldDecorator('btn', {
                    initialValue: undefined,
                    rules: [{ required: false, message: '' }],
                  })(
                    <Button onClick={this.handleQuery} style={{ margin: '4px 15px 20px 0', background: 'rgba(255,255,255,1)' }}>查询</Button>
                  )}
                </FormItem>
              </Col>
              <Col span={2}>
                <FormItem {...formItemLayout}>
                  {getFieldDecorator('newAdd', {
                    initialValue: undefined,
                    rules: [{ required: false, message: '' }],
                  })(
                    <Button icon="plus" onClick={this.handleAdd} style={{ background: 'rgba(247,128,93,1)', color: '#fff', margin: '4px 0 0 0' }}>新增</Button>
                  )}
                </FormItem>
              </Col>
            </Row>
          </Form>
        </div>
        <div style={{ width: '100%', height: '10px', background: '#f0f2f5' }}></div>
        <div style={{ padding: '24px 0 0 0' }} className="table-body-height">
          <Table
            columns={param.columns}
            dataSource={param.data}
            pagination={false}
            rowKey={record => record.key}
            bordered
            style={{ height: store.getState().tableHeight.y + 60 + 'px', overflow: "auto" }}
          />
          <CommonPagination size={this.state.size} pageSize={this.state.pageSize} current={this.state.page} total={this.state.total} search={this.state.search}
            onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.tableData}
            onChange={this.onChange.bind(this)} />
        </div>
        <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='PoorHouseholdInformation'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getMainTableColumns}
                    />
        <PoorConfigModal modalRef={this.modalRef} defaultFlag={this.state.defaultFlag}  propMethod={{ showModal: this.showModal, findData: this.handleQuery }} />
      </Spin>
    )
  }
}
export default Form.create()(PoorHouseholdsConfig);